﻿@using OSBLE.Models.Assignments
@using OSBLE.Areas.AssignmentDetails.ViewModels
@using OSBLE.Models.Courses;
@using OSBLE.Resources
@model AssignmentDetailsViewModel
@{
    ViewBag.Title = "Assignment Details";
    DynamicDictionary headerData = Model.HeaderBuilder.BuildHeader(Model.CurrentAssignment);

    bool HideMail = true;
    if (null == ViewBag.HideMail)
    {
        HideMail = OSBLE.Utility.DBHelper.GetAbstractCourseHideMailValue(ViewBag.ActiveCourseUser.AbstractCourseID);
    }
    else
    {
        HideMail = ViewBag.HideMail;
    }
}
@section AssignmentDetails
{
    <tr>
        <th>
            Due:
        </th>
        <td>
            <time class="utc-time"
                  datetime="@Helpers.DateAsUnixTime(Model.CurrentAssignment.DueDate)"
                  data-original-date="@Helpers.RawDate(Model.CurrentAssignment.DueDate)"
                  data-date-format="MM/DD/YYYY hh:mm A">
                @Model.CurrentAssignment.DueDate.ToShortDateString() @Model.CurrentAssignment.DueDate.ToShortTimeString() (UTC)
            </time>
        </td>
    </tr>
    @foreach (string view in Model.HeaderViews)
    {
        string viewLocation = string.Format("HeaderBuilder/{0}", view);
        @Html.Partial(viewLocation, headerData);
    }
}
@section TableData
{
    @if (Model.Client.AbstractRole.CanGrade)
    {
        CourseUser currentUser = ViewBag.ActiveCourseUser;

        //If preceding assignment team was a discussion, we want to use discussion teams for the team evaluation

        List<IAssignmentTeam> teams = null;
        if (Model.CurrentAssignment.PreceedingAssignment.Type == AssignmentTypes.DiscussionAssignment)
        {
            teams = (from t in Model.CurrentAssignment.PreceedingAssignment.DiscussionTeams
                     orderby t.TeamName ascending
                     select (IAssignmentTeam)t).ToList();
        }
        else
        {
            teams = (from t in Model.CurrentAssignment.PreceedingAssignment.AssignmentTeams
                     orderby t.Team.Name ascending
                     select (IAssignmentTeam)t).ToList();
        }

        HashSet<int> sections = new HashSet<int>();

        foreach (IAssignmentTeam assignmentTeam in teams)
        {
            foreach (TeamMember tm in assignmentTeam.Team.TeamMembers.OrderBy(t => t.CourseUser.Section))
            {
                sections.Add(tm.CourseUser.Section);
            }
        }
        //populate cross section teams //create a list of the multiSections
        List<string> multiSections = currentUser.MultiSection != null ? currentUser.MultiSection.Split(',').ToList() : new List<string>();

        HashSet<IAssignmentTeam> CrossSectionTeam = new HashSet<IAssignmentTeam>();

        foreach (IAssignmentTeam assignmentTeam in teams)
        {
            //Make sure all team members are on the same section.
            int temp;
            bool flagCheck;
            bool sectionFlag;
            temp = assignmentTeam.Team.TeamMembers.FirstOrDefault().CourseUser.Section;
            flagCheck = false;
            sectionFlag = false;

            if (currentUser.Section == -2) //if user in all section, always display users
            {
                sectionFlag = true;
            }

            //populate cross section
            foreach (TeamMember member in assignmentTeam.Team.TeamMembers) //make sure all team members are on the same team.
            {

                //if the current user is a multi section user (not all section)
                if (currentUser.Section == -1)
                {
                    int isInList = multiSections.IndexOf(member.CourseUser.Section.ToString());
                    if (isInList != -1) //if this user's multisection contains this users' section
                    {
                        sectionFlag = true;
                    }
                }

                    //if the current user is a single section user
                else if (currentUser.Section >= 0) //if TA or Instructor is a single section user, check if one of the team members is in their section
                {
                    if (member.CourseUser.Section == currentUser.Section)
                    {
                        sectionFlag = true;
                    }
                }

                //if the teammate we're looking at doesn't have the same section as all others, it's a cross section team
                if (member.CourseUser.Section != temp)
                {
                    flagCheck = true;
                    break;
                }
            }

            if (flagCheck && sectionFlag) //If the team is cross section and the current user has one member of the team in their section, add it to the list off Cross Sections
            {
                CrossSectionTeam.Add(assignmentTeam);
                continue;
            }
        }

        //end population of cross section teams

        //this bool is to determine whether or not there needs to be a row with a section header.
        bool sectionBool = false;

        //check if all teams are cross section teams.
        bool onlyCross = true;

        //only show sections if there are more than 1 section
        bool showSections = false;

        if (sections.Count > 1)
        {
            showSections = true;
        }

        foreach (int section in sections)
        {
            // For TAs, we only want the TA to see students in the section they are in

            if (currentUser != null)
            {
                if (currentUser.AbstractRole.Name == "TA") //see if the user is a TA
                {
                    if (currentUser.Section >= 0) //check if the user is a multi-section user or not
                    {
                        if (section != currentUser.Section) //if not, make sure they are in this section before displaying the grades
                        {
                            continue;
                        }
                    }

                    else if (currentUser.Section == -1)
                    {
                        int isInList = multiSections.IndexOf(section.ToString());
                        if (isInList == -1) //if this user's multisection does not contain this section
                        {
                            continue;
                        }
                    }
                }
            }

            sectionBool = false;

            //Going over each Team. Creating a header row for the team. And under the header row, creating a
            //a row for each user.
            foreach (IAssignmentTeam assignmentTeam in teams)
            {

                //Make sure all team members are on the same team.
                int temp;
                bool flagCheck;
                temp = assignmentTeam.Team.TeamMembers.FirstOrDefault().CourseUser.Section;
                flagCheck = false;

                foreach (TeamMember tm in assignmentTeam.Team.TeamMembers)
                {
                    if (tm.CourseUser.Section != temp)
                    {
                        flagCheck = true;
                        break;
                    }
                }

                if (flagCheck)
                {
                    continue;
                }

                if (assignmentTeam.Team.TeamMembers.FirstOrDefault().CourseUser.Section != section)
                {
                    continue;
                }

                if ((!sectionBool) && showSections)
                {
                    <tr class="SectionRow">
                        <th class="Student" colspan="6">
                            Section: @Html.Raw(section)
                        </th>
                    </tr>
                    sectionBool = true;
                }

                //if you reach here, the page is displaying at least one team that is not cross section
                onlyCross = false;

                if (assignmentTeam.Team.TeamMembers.Count() > 1)
                {
                    <tr>
                        <th class="TeamHeader" colspan="6">

                            @{string actionLink = Url.Action("CreateTeam", "Mail", new { area = "", teamID = assignmentTeam.Team.ID });
                            }
                            @if (!HideMail)
                            {
                                <a href="@actionLink" title="Email this team">@Helpers.MailButton()</a>
                            }
                            @assignmentTeam.Team.Name -
                            @Html.ActionLink("View Evaluations", "TeacherTeamEvaluation", "Assignment", new { precedingTeamId = assignmentTeam.TeamID, TeamEvaluationAssignmentId = Model.CurrentAssignment.ID, area = "" }, new { })
                        </th>
                    </tr>
                }

                //Creating a fake assignment team for each team member. This fake assignment team only has the user we're interested in in the TeamMembers list
                //but has the correct TeamID for the TeamID slot.
                foreach (TeamMember member in assignmentTeam.Team.TeamMembers.OrderBy(t => t.CourseUser.DisplayName(Model.Client.AbstractRoleID, false)).ToList())
                {
                    if (member.CourseUser.AbstractRoleID == (int)CourseRole.CourseRoles.Student)
                    {
                        AssignmentTeam singleUserAssignmentTeam = new AssignmentTeam();
                        singleUserAssignmentTeam.Team = new Team();
                        singleUserAssignmentTeam.Team.TeamMembers.Add(member);
                        singleUserAssignmentTeam.Team.Name = member.CourseUser.DisplayName(Model.Client.AbstractRole);
                        singleUserAssignmentTeam.TeamID = member.TeamID;
                        singleUserAssignmentTeam.Assignment = assignmentTeam.Assignment;
                        singleUserAssignmentTeam.AssignmentID = assignmentTeam.AssignmentID;
                        <tr>
                            <td>
                                @{string actionLink = Url.Action("CreateUser", "Mail", new { area = "", id = member.CourseUser.UserProfileID });}
                                @if (!HideMail)
                                {
                                    <a href="@actionLink" title="Email this user">@Helpers.MailButton()</a>
                                }
                                @member.CourseUser.DisplayName(Model.Client.AbstractRoleID, false)
                            </td>
                            @foreach (string view in Model.TableColumnHeaders.Keys)
                            {
                                DynamicDictionary tableData = Model.TeamTableBuilders[assignmentTeam].BuildTableForTeam(singleUserAssignmentTeam);
                                string viewLocation = string.Format("TableBuilder/{0}", view);
                                @Html.Partial(viewLocation, tableData);
                            }
                        </tr>
                    }
                }
            }
        }

        //if the assignment has teams that are cross section
        if (CrossSectionTeam.Count > 0 && (!onlyCross))
        {
            <tr class="SectionRow">
                <th class="Student" colspan="6">
                    Cross Section Teams:
                </th>
            </tr>
        }

        foreach (IAssignmentTeam assignmentTeam in CrossSectionTeam)
        {
            if (assignmentTeam.Team.TeamMembers.Count() > 1)
            {
                <tr>
                    <th class="TeamHeader" colspan="6">

                        @{string actionLink = Url.Action("CreateTeam", "Mail", new { area = "", teamID = assignmentTeam.Team.ID });
                        }
                        @if (!HideMail)
                        {
                            <a href="@actionLink" title="Email this team">@Helpers.MailButton()</a>
                        }
                        @assignmentTeam.Team.Name -
                        @Html.ActionLink("View Evaluations", "TeacherTeamEvaluation", "Assignment", new { precedingTeamId = assignmentTeam.TeamID, TeamEvaluationAssignmentId = Model.CurrentAssignment.ID, area = "" }, new { })
                    </th>
                </tr>
            }

            //Creating a fake assignment team for each team member. This fake assignment team only has the user we're interested in in the TeamMembers list
            //but has the correct TeamID for the TeamID slot.
            foreach (TeamMember member in assignmentTeam.Team.TeamMembers.OrderBy(t => t.CourseUser.DisplayName(Model.Client.AbstractRoleID, false)).ToList())
            {
                if (member.CourseUser.AbstractRoleID == (int)CourseRole.CourseRoles.Student)
                {
                    AssignmentTeam singleUserAssignmentTeam = new AssignmentTeam();
                    singleUserAssignmentTeam.Team = new Team();
                    singleUserAssignmentTeam.Team.TeamMembers.Add(member);
                    singleUserAssignmentTeam.Team.Name = member.CourseUser.DisplayName(Model.Client.AbstractRole);
                    singleUserAssignmentTeam.TeamID = member.TeamID;
                    singleUserAssignmentTeam.Assignment = assignmentTeam.Assignment;
                    singleUserAssignmentTeam.AssignmentID = assignmentTeam.AssignmentID;
                    <tr>
                        <td>

                            @{string actionLink = Url.Action("CreateUser", "Mail", new { area = "", id = member.CourseUser.UserProfileID });}
                            @if (!HideMail)
                            {
                                <a href="@actionLink" title="Email this user">@Helpers.MailButton()</a>
                            }
                            @member.CourseUser.DisplayName(Model.Client.AbstractRoleID, false)
                        </td>
                        @foreach (string view in Model.TableColumnHeaders.Keys)
                        {

                            DynamicDictionary tableData = Model.TeamTableBuilders[assignmentTeam].BuildTableForTeam(singleUserAssignmentTeam);
                            string viewLocation = string.Format("TableBuilder/{0}", view);
                            @Html.Partial(viewLocation, tableData);
                        }
                    </tr>
                }
            }
        }
    }
}
